package com.ckd.flyingtrip.shared.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polygon;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.activity.BaseActivity;
import com.ckd.flyingtrip.activity.MainActivity;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.HomeIndulgenceBean;
import com.ckd.flyingtrip.shared.bean.SharedCarFenceBean;
import com.ckd.flyingtrip.shared.bean.SharedCarInfoBean;
import com.ckd.flyingtrip.shared.bean.SharedCarLogLanBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.CustomDialog;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class SharedCarActivity extends BaseActivity {

    @BindView(R.id.toolber_color_title)
    TextView title;
    @BindView(R.id.toolber_color_right)
    TextView right;
    @BindView(R.id.activity_sharedcar_mapView)
    MapView mapView;
    @BindView(R.id.activity_sharedcar_icon)
    ImageView icon;
    @BindView(R.id.activity_sharedcar_unlock)
    LinearLayout unlock;
    @BindView(R.id.activity_sharedcar_end)
    LinearLayout end;

    private LocationClient mLocationClient;
    private BaiduMap mBaiduMap;
    private String Latitude = "0.0", Longitude = "0.0";
    private List<LatLng> list_LatLng = new ArrayList<LatLng>();
    private Marker mMarkerA = null, mMarkerB = null;
    private List<Marker> markers = new ArrayList<>();
    private List<Marker> markersB = new ArrayList<>();
    private MarkerOptions option, optionB;

    public static String token = "";
    public static String currentFenceId = "";
    private boolean aBoolean = false, bBoolean = false;

    private CustomDialog.Builder builder;
    private CustomDialog dialog;

    private Handler handler = new Handler();

    private Polygon mPolygon, mPolygon1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sharedcar);
        ButterKnife.bind(this);

        initView();
        initData();
    }

    private void initData() {
        StringRequest request = new StringRequest(Request.Method.POST,
                Constants.shared_sync + BcUtils.getUserInfo().getUserPhone() + "/" + MD5(BcUtils.getUserInfo().getUserPhone() + "243"),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.i("共享APP用户获取token", s);
                        try {
                            JSONObject json = new JSONObject(s);
                            String code = json.getString("code");
                            String message = json.getString("message");
                            if (code.equals("200")) {
                                String data = json.getString("data");
                                JSONObject jsonObject = new JSONObject(data);
                                token = jsonObject.getString("token");
                                initInfo();
                            } else {
                                Tools.toast(message);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initView() {
        title.setText("共享滑板车");
        right.setVisibility(View.VISIBLE);
        right.setText("共享订单");

        initMapBaidu();
        getLocation();
        initMapLocation();

        initDialog();

    }

    Runnable postDelayed = new Runnable() {
        @Override
        public void run() {
            if (mLocationClient != null) {
                mLocationClient.requestLocation();
            }
        }
    };

    private void initDialog() {
        builder = new CustomDialog.Builder(this)
                .cancelTouchout(false)
                .view(R.layout.dialog_me_client)
                .widthDimenRes(R.dimen.x520)
                .heightDimenRes(R.dimen.y360)
                .style(R.style.Dialog)
                .addViewOnclick(R.id.dialog_me_client_btn1, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                })
                .addViewOnclick(R.id.dialog_me_client_btn2, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        aBoolean = true;
                        if (mLocationClient != null) {
                            mLocationClient.requestLocation();
                        }

                        handler.removeCallbacks(postDelayed);
                        dialog.dismiss();
                    }
                });

        dialog = builder.build();

        TextView textView = builder.getView(R.id.dialog_me_client_textView);
        textView.setText("确定结束用车吗？");
    }

    private void initMapBaidu() {
        mapView.showZoomControls(false);
        mapView.showScaleControl(false);
        mBaiduMap = mapView.getMap();

        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                MapView.setMapCustomEnable(true);
            }
        });

        View child = mapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setTrafficEnabled(false);
        mBaiduMap.setBuildingsEnabled(false);

        BaiduMap.OnMapStatusChangeListener listener = new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                Log.e("sss", "-------------------onMapStatusChangeStart");
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
                Log.e("sss", "-------------------onMapStatusChangeStart--------" + i);
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
                Log.e("sss", "-------------------onMapStatusChange");
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                Log.e("sss", "-------------------onMapStatusChangeFinish");
                Latitude = mapStatus.target.latitude + "";
                Longitude = mapStatus.target.longitude + "";
                Log.e("sss", Latitude + "       onMapStatusChangeFinish      " + Longitude);
                initLogLan();
            }
        };

        mBaiduMap.setOnMapStatusChangeListener(listener);
    }

    private void getLocation() {
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) this.getSystemService(serviceName);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        updateLocation(location);
    }

    private void updateLocation(Location location) {
        Log.e("sss", "-----------------------" + location);
        if (location != null) {
            Latitude = location.getLatitude() + "";
            Longitude = location.getLongitude() + "";

            if (!bBoolean) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                LatLng pos = new LatLng(latitude, longitude);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(pos).zoom(16.0f);
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(builder.build());
                mBaiduMap.animateMapStatus(mapStatusUpdate);
                Log.e("sss", location.getLatitude() + "         ----        " + location.getLongitude());
                bBoolean = true;
            }
            initLogLan();

        } else {
//            Toast.makeText(this, "无法获取到位置信息", Toast.LENGTH_SHORT).show();
        }
    }

    private void initMapLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setIsNeedAddress(true);
        option.setLocationNotify(false);
        option.setIsNeedLocationDescribe(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        option.setAddrType("all");
        option.setProdName("ipark");
        mLocationClient.registerLocationListener(new MyLocationListener());
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                Log.e("sss", location.getLatitude() + "                 " + location.getLongitude());
                Latitude = location.getLatitude() + "";
                Longitude = location.getLongitude() + "";
                if (!bBoolean) {
                    LatLng pos = new LatLng(location.getLatitude(), location.getLongitude());
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(pos).zoom(16.0f);
                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(builder.build());
                    mBaiduMap.animateMapStatus(mapStatusUpdate);
                    bBoolean = true;
                }

//                LatLng pos = new LatLng(41.1002822485, 122.95233135732);
//                MapStatus.Builder builder = new MapStatus.Builder();n
//                builder.target(pos).zoom(16.0f);
//                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(builder.build());
//                mBaiduMap.animateMapStatus(mapStatusUpdate);

                initLogLan();
                if (aBoolean) {
                    aBoolean = false;
                    initEnd();
                }

                for (int i = 0; i < markersB.size(); i++) {
                    markersB.get(i).remove();
                }
                LatLng latLng = new LatLng(Double.parseDouble(Latitude), Double.parseDouble(Longitude));
                View view_mark = LayoutInflater.from(SharedCarActivity.this).inflate(R.layout.layout_map_maker, null);
                ImageView ivBattery = (ImageView) view_mark.findViewById(R.id.iv_battery);
                ivBattery.setImageResource(R.mipmap.activity_sharedcar_icon4);
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view_mark);
                optionB = new MarkerOptions().icon(bitmap).position(latLng);
                mMarkerB = (Marker) (mBaiduMap.addOverlay(optionB));
                markersB.add(mMarkerB);
                mMarkerB.setPerspective(true);
                mMarkerB.setToTop();
                mMarkerB.setFlat(true);
                optionB.zIndex(999);
            }
        }
    }

    private void initLogLan() {
//        https://share.user.ytxiaohe.com/app/241/bike/list?latitude=38.994944&&longitude=117.352678
//        mBaiduMap.clear();
        for (int i = 0; i < markers.size(); i++) {
            markers.get(i).remove();
        }
        if (mPolygon1 == null)
            initAgentFence();
        double[] doubles = bdToGaoDe(Double.parseDouble(Latitude), Double.parseDouble(Longitude));
        StringRequest request = new StringRequest(Request.Method.GET, Constants.shared_list + "?latitude=" + doubles[1] + "&&longitude=" + doubles[0], new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("共享车辆列表", s);
                SharedCarLogLanBean bean = new Gson().fromJson(s, SharedCarLogLanBean.class);
                if (bean.getCode().equals("200")) {
                    currentFenceId = bean.getData().getCurrentFenceId();
                    list_LatLng.clear();
                    for (int i = 0; i < bean.getData().getBike().size(); i++) {
                        double[] doubles = gaoDeToBaidu(Double.parseDouble(bean.getData().getBike().get(i).getLongitude()), Double.parseDouble(bean.getData().getBike().get(i).getLatitude()));
                        LatLng l = new LatLng(doubles[1], doubles[0]);
//                        LatLng l = new LatLng(Double.parseDouble(bean.getData().getBike().get(i).getLatitude()),
//                                Double.parseDouble(bean.getData().getBike().get(i).getLongitude()));
                        list_LatLng.add(l);
                    }
//                    LatLng l = new LatLng(41.701066, 123.48972);
//                    LatLng l1 = new LatLng(41.700041, 123.490922);
//                    LatLng l2 = new LatLng(41.700938, 123.493153);
//                    LatLng l3 = new LatLng(41.701707, 123.491093);
//                    LatLng l4 = new LatLng(41.698631, 123.485343);
//                    list_LatLng.add(l);
//                    list_LatLng.add(l1);
//                    list_LatLng.add(l2);
//                    list_LatLng.add(l3);
//                    list_LatLng.add(l4);
                    for (int i = 0; i < list_LatLng.size(); i++) {
                        View view_mark = LayoutInflater.from(SharedCarActivity.this).inflate(R.layout.layout_map_maker, null);
                        ImageView ivBattery = (ImageView) view_mark.findViewById(R.id.iv_battery);
                        ivBattery.setImageResource(R.mipmap.activity_sharedcar_icon1);
                        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view_mark);
                        option = new MarkerOptions().icon(bitmap).position(list_LatLng.get(i));
                        mMarkerA = (Marker) (mBaiduMap.addOverlay(option));
                        markers.add(mMarkerA);
                        mMarkerA.setPerspective(true);
//                        mMarkerA.setToTop();
                        mMarkerA.setFlat(true);
                        option.zIndex(998);
                    }

                    if (mPolygon == null) {
                        for (int i = 0; i < bean.getData().getFence().size(); i++) {
                            String s1 = bean.getData().getFence().get(i).getFencePoints();
                            String[] strings = s1.split("\\|");
                            for (int j = 0; j < strings.length; j++) {
                                if (!strings[j].equals("")) {
                                    String[] strings1 = strings[j].split(";");
                                    List<LatLng> latLngList = new ArrayList<LatLng>();
                                    for (int x = 0; x < strings1.length; x++) {
                                        String[] strings2 = strings1[x].split(",");
                                        double[] doubles = gaoDeToBaidu(Double.parseDouble(strings2[0]), Double.parseDouble(strings2[1]));
                                        LatLng latLng = new LatLng(doubles[1], doubles[0]);
//                                        LatLng latLng = new LatLng(Double.parseDouble(strings2[1]), Double.parseDouble(strings2[0]));
                                        latLngList.add(latLng);
                                    }
                                    OverlayOptions ooPolygon = null;
                                    switch (bean.getData().getFence().get(i).getFenceType()) {
                                        case "1":
                                            ooPolygon = new PolygonOptions()
                                                    .points(latLngList)
                                                    .stroke(new Stroke(2, Color.argb(255, 252, 253, 17)))
                                                    .fillColor(Color.argb(50, 252, 253, 17));
                                            break;
                                        case "2":
                                            ooPolygon = new PolygonOptions()
                                                    .points(latLngList)
                                                    .stroke(new Stroke(2, Color.argb(255, 245, 51, 2)))
                                                    .fillColor(Color.argb(50, 245, 51, 2));
                                            break;
                                        case "3":
                                            ooPolygon = new PolygonOptions()
                                                    .points(latLngList)
                                                    .stroke(new Stroke(2, Color.argb(255, 0, 0, 0)))
                                                    .fillColor(Color.argb(50, 0, 0, 0));
                                            break;
                                    }
                                    mPolygon = (Polygon) mBaiduMap.addOverlay(ooPolygon);
                                }
                            }
                        }
                    }
                } else {
                    Tools.toast(bean.getMessage());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> mHeader = new HashMap<String, String>();
                return mHeader;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initAgentFence() {
        double[] doubles = bdToGaoDe(Double.parseDouble(Latitude), Double.parseDouble(Longitude));
        StringRequest request = new StringRequest(Request.Method.GET, Constants.shared_fence + "?latitude=" + doubles[1] + "&&longitude=" + doubles[0], new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("获取共享代理商所有运营围栏", s);
                SharedCarFenceBean bean = new Gson().fromJson(s, SharedCarFenceBean.class);
                if (bean.getCode().equals("200")) {
                    for (int i = 0; i < bean.getData().getFenceList().size(); i++) {
                        String s1 = bean.getData().getFenceList().get(i).getFencePoints();
                        String[] strings = s1.split("\\|");
                        for (int j = 0; j < strings.length; j++) {
                            if (!strings[j].equals("")) {
                                String[] strings1 = strings[j].split(";");
                                List<LatLng> latLngList = new ArrayList<LatLng>();
                                for (int x = 0; x < strings1.length; x++) {
                                    String[] strings2 = strings1[x].split(",");
                                    double[] doubles = gaoDeToBaidu(Double.parseDouble(strings2[0]), Double.parseDouble(strings2[1]));
                                    LatLng latLng = new LatLng(doubles[1], doubles[0]);
//                                    LatLng latLng = new LatLng(Double.parseDouble(strings2[1]), Double.parseDouble(strings2[0]));
                                    latLngList.add(latLng);
                                }
                                OverlayOptions ooPolygon = new PolygonOptions()
                                        .points(latLngList)
                                        .stroke(new Stroke(2, Color.argb(255, 91, 91, 242)))
                                        .fillColor(Color.argb(50, 91, 91, 242));
                                mPolygon1 = (Polygon) mBaiduMap.addOverlay(ooPolygon);
                            }
                        }
                    }
                } else {
                    Tools.toast(bean.getMessage());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> mHeader = new HashMap<String, String>();
                return mHeader;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    @OnClick({R.id.toolber_color_back, R.id.toolber_color_right, R.id.activity_sharedcar_unlock, R.id.activity_sharedcar_end,
            R.id.activity_sharedcar_help, R.id.activity_sharedcar_refresh})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.toolber_color_back:
                handler.removeCallbacks(postDelayed);
                finish();
                break;
            case R.id.toolber_color_right:
                handler.removeCallbacks(postDelayed);
                intent = new Intent(this, SharedCarOrderActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_sharedcar_unlock:
                initZxing();
                break;
            case R.id.activity_sharedcar_end:
                dialog.show();
                break;
            case R.id.activity_sharedcar_help:
                handler.removeCallbacks(postDelayed);
                intent = new Intent(this, SharedCarHelpActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_sharedcar_refresh:
                toast("正在定位中 请稍等...");
                bBoolean = false;
                if (mLocationClient != null) {
                    mLocationClient.requestLocation();
                }
                break;
        }
    }

    private void initEnd() {
        double[] doubles = bdToGaoDe(Double.parseDouble(Latitude), Double.parseDouble(Longitude));
        StringRequest request = new StringRequest(Request.Method.GET,
                Constants.shared_end + "?latitude=" + doubles[1] + "&&longitude=" + doubles[0] + "&confirm=confirm",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        dismisProgressDialog();
                        Log.i("共享关锁结束行程", s);
                        try {
                            JSONObject json = new JSONObject(s);
                            String code = json.getString("code");
                            String message = json.getString("message");
                            Intent intent;
                            switch (code) {
                                case "30":
                                    intent = new Intent(SharedCarActivity.this, SharedCarPayActivity.class);
                                    startActivity(intent);
                                    break;
                                case "100":
                                    if (message.equals("行程已结束，请刷新客户端")) {
                                        intent = new Intent(SharedCarActivity.this, SharedCarPayActivity.class);
                                        startActivity(intent);
                                    } else
                                        Tools.toast(message);
                                    break;
                                default:
                                    Tools.toast(message);
                                    break;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> mHeader = new HashMap<String, String>();
                mHeader.put("TOKEN_XCX_SHARE", token);
                return mHeader;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initZxing() {
        Intent intent = new Intent(SharedCarActivity.this, CaptureActivity.class);
        ZxingConfig config = new ZxingConfig();
        config.setShowAlbum(false);
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, Constants.ZXINGE_MAIN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.ZXINGE_MAIN && resultCode == this.RESULT_OK) {
            String content = data.getStringExtra(Constant.CODED_CONTENT);
            Log.e("共享二维码", content);
            initStart(content);
        }
    }

    private void initStart(String content) {
        StringRequest request = new StringRequest(Request.Method.GET, Constants.shared_start + "?qrCode=" + content, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("开始骑行：根据二维码开始骑行", s);

                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String message = json.getString("message");
                    if (code.equals("200")) {
                        unlock.setVisibility(View.GONE);
                        end.setVisibility(View.VISIBLE);
                        Tools.toast("开锁成功！");
                    } else {
                        Tools.toast(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> mHeader = new HashMap<String, String>();
                mHeader.put("TOKEN_XCX_SHARE", token);
                return mHeader;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    public String MD5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private void initInfo() {
        StringRequest request = new StringRequest(Request.Method.GET, Constants.shared_info, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("共享用户信息", s);
                SharedCarInfoBean bean = new Gson().fromJson(s, SharedCarInfoBean.class);
                if (bean.getCode().equals("200")) {
                    if (bean.getData().getProcessTrip() == null) {
                        unlock.setVisibility(View.VISIBLE);
                        end.setVisibility(View.GONE);
                    } else {
                        unlock.setVisibility(View.GONE);
                        end.setVisibility(View.VISIBLE);
                    }
                } else
                    Tools.toast(bean.getMessage());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> mHeader = new HashMap<String, String>();
                mHeader.put("TOKEN_XCX_SHARE", token);
                return mHeader;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
        handler.postDelayed(postDelayed, 10000);
        if (token != null)
            initInfo();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        handler.removeCallbacks(postDelayed);
        return super.onKeyDown(keyCode, event);
    }

    private double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    private double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }
}
